package com.ssk.sh.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusPropertiesCustomizer;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.handlers.MybatisEnumTypeHandler;
import com.baomidou.mybatisplus.extension.incrementer.PostgreKeyGenerator;
import com.github.pagehelper.PageInterceptor;
import java.util.Map;
import java.util.Properties;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.wrapper.MapWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author ssk
 * @date 2025/6/12
 **/
@Configuration
@MapperScan("com.ssk.*.dao*")

public class MybatisPlusConfig {

    @Bean
    PostgreKeyGenerator postgreKeyGenerator() {
        return new PostgreKeyGenerator();
    }


    /**
     * 添加分页插件
     */
//    @Bean
//    public MybatisPlusInterceptor mybatisPlusInterceptor() {
//        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//        // 添加分页插件, 如果配置多个插件, 切记分页最后添加
//        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
//        // 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbTypereturn interceptor;
//        return interceptor;
//
//    }
    @Bean
    public MybatisPlusPropertiesCustomizer mybatisPlusPropertiesCustomizer() {
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteEnumUsingToString);
        return properties -> {
            // 配置分页插件
            GlobalConfig globalConfig = properties.getGlobalConfig();
            globalConfig.setBanner(true);
            MybatisPlusProperties.CoreConfiguration configuration = new MybatisPlusProperties.CoreConfiguration();
            configuration.setDefaultEnumTypeHandler(MybatisEnumTypeHandler.class);
//            configuration.setMapUnderscoreToCamelCase(true);
            properties.setConfiguration(configuration);

        };
    }
//    @Bean
//    public MybatisPlusInterceptor mybatisPlusInterceptor() {
//        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//        // 添加非法SQL拦截器
//        interceptor.addInnerInterceptor(new IllegalSQLInnerInterceptor());
//        return interceptor;
//    }

//    @Bean
//    public Jackson2ObjectMapperBuilderCustomizer customizer() {
//        return builder -> builder.featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
//    }


    @Bean
    public PageInterceptor pageInterceptor() {
        PageInterceptor pageInterceptor = new PageInterceptor();
        // 通过 Properties 设置与 application.yaml 对应的配置参数
        Properties properties = new Properties();
        // 对应 reasonable: true（是否启用合理化参数，当 pageNum<1 或 >总页数时自动调整）
        properties.setProperty("reasonable", "true");
        // 对应 support-methods-arguments: true（是否支持通过方法参数传递分页参数）
        properties.setProperty("supportMethodsArguments", "true");
        // 对应 params: countSql（count 查询的参数名）
        properties.setProperty("params", "countSql");
        // 对应 helperDialect: postgresql（数据库方言，用于生成分页 SQL）
        properties.setProperty("helperDialect", "postgresql");
        // 对应 banner: true（是否显示 PageHelper 启动 banner）
        properties.setProperty("banner", "true");

        pageInterceptor.setProperties(properties);
        return pageInterceptor;
    }

//    @Bean
//    @ConfigurationProperties("spring.datasource.dynamic.datasource.user")
//    public DataSourceProperty userDyDataSourceProperty() {
//        return new DataSourceProperty();
//
//    }
//
//    @Bean
//    @ConfigurationProperties("spring.datasource.dynamic.datasource.chat")
//    public DataSourceProperty chatDyDataSourceProperty() {
//        return new DataSourceProperty();
//    }

//
//    @Bean(name = "userDyDataSource")
//    @Primary
//    public DataSource userDataSource(@Qualifier("userDyDataSourceProperty") DataSourceProperty dataSourceProperty) {
//        return DataSourceBuilder.create()
//                .url(dataSourceProperty.getUrl())
//                .username(dataSourceProperty.getUsername())
//                .password(dataSourceProperty.getPassword())
//                .driverClassName(dataSourceProperty.getDriverClassName())
//                .build();
//    }
//
//    @Bean(name = "chatDyDataSource")
//    public DataSource chatDataSource(@Qualifier("chatDyDataSourceProperty") DataSourceProperty properties) {
//        return DataSourceBuilder.create()
//                .url(properties.getUrl())
//                .username(properties.getUsername())
//                .password(properties.getPassword())
//                .driverClassName(properties.getDriverClassName())
//                .build();
//    }
//
//    @Bean("userSqlSessionFactory")
//    @Primary
//    public SqlSessionFactory userSqlSessionFactory(@Qualifier("userDyDataSource") DataSource dataSource) throws Exception {
//        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
//        factoryBean.setDataSource(dataSource);
//
//        // 手动设置驼峰映射
//        MybatisConfiguration configuration = new MybatisConfiguration();
//        configuration.setMapUnderscoreToCamelCase(true);
//        factoryBean.setConfiguration(configuration);
//
//        return factoryBean.getObject();
//    }
//
//    @Bean("chatSqlSessionFactory")
//    public SqlSessionFactory chatSqlSessionFactory(@Qualifier("chatDyDataSource") DataSource dataSource) throws Exception {
//        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
//        factoryBean.setDataSource(dataSource);
//
//        // 手动设置驼峰映射
//        MybatisConfiguration configuration = new MybatisConfiguration();
//        configuration.setMapUnderscoreToCamelCase(true);
//        factoryBean.setConfiguration(configuration);
//
//        return factoryBean.getObject();
//    }

//    @Bean
//    public ConfigurationCustomizer configurationCustomizer() {
//        return configuration ->
//        {

    /// /            configuration.setMapUnderscoreToCamelCase(true); /            configuration.setObjectWrapperFactory(new MapWrapperFactory());
//        };
//    }

    static class MapWrapperFactory implements ObjectWrapperFactory {

        @Override
        public boolean hasWrapperFor(Object object) {
            return object instanceof Map;
        }

        @Override
        public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
            return new CustomWrapper(metaObject, (Map<String, Object>) object);
        }
    }

    static class CustomWrapper extends MapWrapper {

        public CustomWrapper(MetaObject metaObject, Map<String, Object> map) {
            super(metaObject, map);
        }

        @Override
        public String findProperty(String name, boolean useCamelCaseMapping) {
            if (useCamelCaseMapping) {
                return toCamelCase(name);
            }
            return name;
        }

        private String toCamelCase(String inputString) {
            StringBuilder sb = new StringBuilder();
            boolean nextUpperCase = false;
            for (int i = 0; i < inputString.length(); i++) {
                char c = inputString.charAt(i);
                if (c == '_') {
                    nextUpperCase = true;
                } else {
                    if (nextUpperCase) {
                        sb.append(Character.toUpperCase(c));
                        nextUpperCase = false;
                    } else {
                        sb.append(Character.toLowerCase(c));
                    }
                }
            }
            return sb.toString();
        }
    }
}
